# coding=utf-8
from uuid import uuid4

from common import orm
from common.mch.db import encode_password
from common.mch.model import MchAccount
from common.utils import track_logging
from common.utils.db import list_object, get, upsert, delete
from common.utils.decorator import sql_wrapper

_LOGGER = track_logging.getLogger(__name__)

DEFAULT_PASSWD = '123456'


@sql_wrapper
def get_mch(id):
    return get(MchAccount, id)


@sql_wrapper
def upsert_mch(info, id=None):
    return upsert(MchAccount, info, id)


@sql_wrapper
def create_mch(info, id=None):
    if 'password' not in info:
        info['password'] = encode_password(DEFAULT_PASSWD)
    if 'api_key' not in info or not info['api_key']:
        info['api_key'] = uuid4().hex
    info['enabled'] = 1
    return upsert(MchAccount, info, id)


@sql_wrapper
def list_mch(query_dct):
    return list_object(query_dct, MchAccount)


@sql_wrapper
def update_status(mch_id, status):
    MchAccount.query.filter(MchAccount.id == mch_id).update({'enabled': status})
    orm.session.commit()
    return {}


@sql_wrapper
def delete_mch(id):
    delete(MchAccount, id)


@sql_wrapper
def delete_mch(mch_id):
    MchAccount.query.filter(MchAccount.id == mch_id).update({'deleted': 1})
    orm.session.commit()
    return {}
